﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Collections;
using System.Text;
using System.Reflection;
using System.IO;
using System.Threading;

using Commons;

namespace Mobile
{
    public class PageBase : System.Web.UI.Page
    {
        #region 私有变量
        private int _UserRightCode = -1; // 默认是无权限

        /// <summary>
        /// GridView空数据行的现实文字
        /// </summary>
        private const string EMPTY_DATA_STYLE = "对不起没有任何数据";

        #endregion

        #region 构造函数
        public PageBase()
        {
            ViewState["sort"] = "desc";//排序使用

            //检查是否超时
            Init += new EventHandler(CheckSessionTimeOut);
            //检查是否有权限
            Init += new EventHandler(CheckRightAuth);

            //检查是否禁用（在超时检查之后）
            //Init += new EventHandler(CheckLoginNoEntry);
            //检测是否强制修改密码
            //Init += new EventHandler(CheckModifyPwd);
            //检查绑定安全项
            //Init += new EventHandler(CheckBindSafe);

            //注册脚本(必须在验证权限之后，因为验证权限时设置了_ModuleInfo)
            //Init += new EventHandler(SendScript);
            //设置页面缓存
            //Load += new EventHandler(SetNoCache);
            //刷新票证计数（用于检测是否刷新）
            //PreRender += new EventHandler(RefreshPage_PreRender);
            //Load += new EventHandler(CheckRefresh);
        }
        
        //取消缓存
        public void SetNoCache(object sender, EventArgs e)
        {
            NoCache();
        }

        #region 注册和发送脚本
        protected void SendScript(object sender, EventArgs e)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), Page.UniqueID, GetAllScript());
        }

        protected virtual string GetAllScript()
        {
            StringBuilder sb = new StringBuilder();
            //注册子窗口容器
            sb.Append("var __windowArray_dx = new Array();");
            //注册打开窗口脚本
            sb.Append(ScriptBuilder.GetOpenWindowScript());
            //注册关闭所有打开窗口的脚本
            sb.Append(ScriptBuilder.GetCloseAllWindowScript());
            //获取top窗口的函数
            sb.Append(ScriptBuilder.GetTopWindow());
            //获取注册事件函数
            sb.Append(ScriptBuilder.GetAddEvent());
            //获取移除时间函数
            sb.Append(ScriptBuilder.GetRemoveEvent());
            //注册页面onunload事件的脚本,onunload时关闭所有打开窗口
            sb.Append("if (_addEvent) _addEvent(window,'unload',_closeAllWindows);");
            return ScriptBuilder.GetScriptBlock(sb.ToString());
        }

        #endregion

        public void CheckLoginNoEntry(object sender, EventArgs e)
        {
            //Dx.Users.IUsers dal = new Dx.Users.Users();
            //string UserId = GetParaValue("UserId");
            //if (!string.IsNullOrEmpty(UserId) && !dal.GetOperUserEnabled(UserId))
            //{
            //    Commons.JScript.MainRedirect("操作超时，系统将安全退出，请重新登录。", ResolveUrl("~/SignOut.aspx"));

            //    Response.End();
            //}
        }

        public void CheckRightAuth(object sender, EventArgs e)
        {
            string currentpath = Request.PhysicalPath.Substring(Request.PhysicalApplicationPath.Length, (Request.PhysicalPath.Length - Request.PhysicalApplicationPath.Length)).Replace('\\', '/');

            Hashtable _ModuleInfo = PhoneBook.Manage.Manage.GetSysModulesByUrl(currentpath);
            string SysMid = string.Empty;
            if (_ModuleInfo != null)
                SysMid = Commons.StrUtil.FormatValue(_ModuleInfo["moduleid"]);

            if (!string.IsNullOrEmpty(SysMid))
            {
                //记录下模块ID
                Session["ModuleId"] = SysMid;
            }
            else
            {
                SysMid = Session["ModuleId"] == null ? "" : Session["ModuleId"].ToString();
            }

            if (!string.IsNullOrEmpty(SysMid))
            {
                int Right = 0;
                string[] strLogin = new string[]
				                       {
				                           SysMid,
				                           GetParaValue("UserId")
			                           };
                Right = PhoneBook.Manage.Manage.getUserModuleRight(GetParaValue("UserId"), SysMid);
                _UserRightCode = Right;
                if (UserRightCode <= 0)
                {
                    //string GotoPath = Request.RawUrl.Replace(currentpath, "NoPower.aspx");
                    Response.Redirect(ResolveUrl("~/NoPower.aspx"));
                    Response.End();
                }
                Hashtable sysmodule = PhoneBook.Manage.sysModule.get(SysMid);
                if (sysmodule != null)
                {
                    //记录最后一次的模块地址
                    Session["LastModuleUrl"] = sysmodule["urladdress"];
                }
            }
            else
                _UserRightCode = 0;

        }

        public void CheckSessionTimeOut(object sender, EventArgs e)
        {
            if (Session["UserId"] == null)
            {
                //string currentpath = Request.PhysicalPath.Substring(Request.PhysicalApplicationPath.Length, (Request.PhysicalPath.Length - Request.PhysicalApplicationPath.Length)).Replace('\\', '/');
                //string GotoPath = Request.RawUrl.Replace(currentpath, "SignOut.aspx");GotoPath
                //Dx.Common.Jscript.AlertAndRedirect("操作超时，系统将安全退出，请重新登录。", ResolveUrl("~/SignOut.aspx"));
                Commons.JScript.MainRedirect("操作超时，系统将安全退出，请重新登录。", ResolveUrl("~/SignOut.aspx"));

                Response.End();
            }
        }
        #endregion

        #region 定义属性
        /// <summary>
        ///  权限：-1表示无权访问，0表示浏览，1表示查询，2表示添加，3表示修改，4表示删除
        /// </summary>
        public int UserRightCode
        {
            get { return _UserRightCode; }
        }

        #endregion

        #region 获取页面参数的值



        /// <summary>
        /// 获取页面参数的值
        /// </summary>
        /// <param name="oSession">Page.Session</param>
        /// <param name="oRequest">Page.Request</param>
        /// <param name="paraName">参数名称</param>
        /// <returns>参数值，字符串形式</returns>
        private string GetParaValue(HttpSessionState oSession, HttpRequest oRequest, string paraName)
        {
            string strValue = "0";

            // 如果Session中能够找到相应的参数值，则返回参数值



            try
            {
                strValue = oSession[paraName].ToString();
            }
            catch (NullReferenceException)
            {
                strValue = "";
            }
            //如果Session中不存在，从Request中寻找。



            if (strValue == null || strValue == "")
            {
                try
                {
                    strValue = oRequest[paraName].ToString();
                }
                catch (NullReferenceException)
                {
                    strValue = "";
                }
                //均为空时，返回空字符串。



                if (strValue == null || strValue == "")
                    strValue = "";
            }
            return strValue;
        }
        #endregion

        #region 获取页面参数的值



        /// <summary>
        /// 获取页面参数的值
        /// </summary>
        /// <param name="paraName">参数名称</param>
        /// <returns>参数值，字符串形式</returns>
        public string GetParaValue(string paraName)
        {
            if (Session[paraName] != null)
                return Session[paraName].ToString();
            else
                return "";
            //return GetParaValue(Session, Request, paraName);
        }
        #endregion

        #region 不启用缓存


        /// <summary>
        /// 不启用缓存
        /// </summary>
        public void NoCache()
        {
            //不启用缓存
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddDays(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
        }
        #endregion

        #region 根据日期生成标准ID号方法(24小时制)
        /// <summary>
        /// 根据日期生成标准ID号方法,格式为yyyyMMddhhmmssff
        /// </summary>
        /// <returns>string</returns>
        public string StandardSh()
        {
            string Id = Commons.StringUtil.GetID_14();//DateTime.Now.ToString("yyMMddHHmmssff");
            return Id;
        }
        #endregion

        #region 当前的排序表达式
        /// <summary>
        /// 在GridView的RowCommand事件中赋值
        /// if (e.CommandName.ToLower() == "sort")
        ///        {
        ///            gvSortExpression = e.CommandArgument.ToString() + " " + ViewState["sort"].ToString();
        ///            return;
        ///        }
        /// </summary>
        public string gvSortExpression
        {
            set { ViewState["gvSortExpression"] = value; }
            get
            {
                if (ViewState["gvSortExpression"] == null)
                    return string.Empty;
                else
                    return ViewState["gvSortExpression"].ToString();
            }
        }
        #endregion

        #region 设置表格排序 此属性已过期。不再使用。
        public DataTable GridViewDataSource
        {
            get
            {
                return null;
            }
            set
            {

            }
        }


        public void SortGridView(ref GridView gv, DataTable dt, GridViewSortEventArgs e)
        {

            //if (dt == null || dt.Rows.Count <= 0) return;

            string sortDirection = "";
            string sortExpression = e.SortExpression;
            if (ViewState["sort"].ToString().ToLower() == "asc")
            {
                ViewState["sort"] = "desc";
                sortDirection = "asc";
            }
            else
            {
                sortDirection = "desc";
                ViewState["sort"] = "asc";
            }

            //DataView dv = dt.DefaultView;

            //dv.Sort = e.SortExpression + " " + sortDirection;
            //gv.DataSource = dv;
            //gv.DataBind();
            QueryData();
        }
        #endregion

        #region 排序时显示排序方向的图标
        public void ShowSortedIcon(GridView gvData, GridViewRow gvRow)
        {
            //此方法已移除，不再使用。
        }
        #endregion

        #region 设置表格分页

        /// <summary>
        /// 绑定分页
        /// </summary>
        public void SetDivePage(ref GridView gv, ref Mobile.Controls.GVPageManager gvm)
        {
            int RecordNum = 10;
            SetDivePage(ref gv, ref gvm, RecordNum);
        }

        /// <summary>
        /// 绑定分页
        /// </summary>
        public void SetDivePage(ref GridView gv, ref Mobile.Controls.GVPageManager gvm, int RecordNum)
        {
            //绑定事件
            Mobile.Controls.BindDataDelegate f = new Mobile.Controls.BindDataDelegate(QueryData);
            //设置分页
            SetDivePage(ref gv, ref gvm, f, RecordNum);
        }

        /// <summary>
        /// 绑定分页
        /// </summary>
        public void SetDivePage(ref GridView gv, ref Mobile.Controls.GVPageManager gvm, Mobile.Controls.BindDataDelegate f, int RecordNum)
        {
            //允许分页
            gv.AllowPaging = true;
            //分页大小
            gv.PageSize = RecordNum;
            //设置分页
            gvm.SetTarget(gv, f, RecordNum);
            //重现空行
            RenderGridViewNullRow(ref gv, ref gvm);
            //行数据绑定事件
            gv.RowDataBound += GridViewRowDataBound;
            //行命令事件
            gv.RowCommand += GridViewRowCommand;

            //允许排序
            gv.AllowSorting = true;
            //排序事件
            gv.Sorting += GridViewSorting;
            //数据绑定前
            gv.DataBinding += new EventHandler(GridViewDataBinding);
        }

        public virtual void QueryData()
        {
        }

        #endregion

        #region 绑定数据
        public void GVDataBind(ref GridView gv, ref Mobile.Controls.GVPageManager gvm, DataSet ds)
        {
            GVDataBind(ref gv, ref gvm, ds, "", false);
        }
        public void GVDataBind(ref GridView gv, ref Mobile.Controls.GVPageManager gvm, DataSet ds, string filter, bool ShowFooter)
        {
            //gv.CssClass = "tablegridview";
            //gv.RowStyle.CssClass = "tablegridview_row";
            //gv.HeaderStyle.CssClass = "tablegridview_header";
            //gv.FooterStyle.CssClass = "tablegridview_Footer";
            //gv.CssClass = "datalist2";

            if ((ds != null) && (ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0))
                DataUtil.DataFilter(ds, filter, gvSortExpression);

            if ((ds == null) || (ds.Tables.Count == 0) || (ds.Tables[0].Rows.Count == 0))
            {
                //gv.CssClass = "datalist2";
                gv.AllowSorting = false;
                gv.ShowFooter = false;

                DataTable dt = new DataTable();
                dt.Columns.Clear();
                for (int i = 0; i < gv.Columns.Count; i++)
                {
                    string DataName = "";
                    try
                    {
                        DataName = ((BoundField)gv.Columns[i]).DataField;
                    }
                    catch
                    {
                        DataName = i.ToString();
                    }
                    if (dt.Columns.IndexOf(DataName) == -1)
                    {
                        dt.Columns.Add(new DataColumn(DataName));
                    }
                    else
                    {
                        dt.Columns.Add(new DataColumn(i.ToString()));
                    }
                }
                for (int i = 0; i < gv.DataKeyNames.Length; i++)
                {
                    string DataName = "";
                    try
                    {
                        DataName = gv.DataKeyNames[i];
                    }
                    catch
                    {

                    }
                    if (dt.Columns.IndexOf(DataName) == -1)
                    {
                        dt.Columns.Add(new DataColumn(DataName));
                    }
                    else
                    {
                        dt.Columns.Add(new DataColumn("0" + i.ToString()));
                    }

                }
                dt.Rows.Add("");
                //this.GridViewDataSource = null;
                gv.DataSource = dt;

                #region 使用空行绑定数据前解除事件，绑定后再重新挂事件
                object _event = null;
                try
                {
                    _event = BackupEvent(gv, "RowDataBound");
                    ClearEvent(gv, "RowDataBound");
                    gv.DataBind();
                }
                catch { }
                finally
                {
                    RestoreEvent(gv, "RowDataBound", _event);
                }
                #endregion

                //gv.Rows[0].Cells.Clear();
                //gv.Rows[0].Cells.Add(new TableCell());
                if (gv.Rows.Count == 0) return;
                while (gv.Rows[0].Cells.Count >= 1)
                {
                    gv.Rows[0].Cells.RemoveAt(0);
                }
                TableCell tc = new TableCell();
                gv.Rows[0].Cells.Add(tc);

                gv.Rows[0].Cells[0].ColumnSpan = gv.Columns.Count;
                gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                if (string.IsNullOrEmpty(gv.EmptyDataText))
                    gv.Rows[0].Cells[0].Text = EMPTY_DATA_STYLE;
                else
                    gv.Rows[0].Cells[0].Text = gv.EmptyDataText;
                gvm.Visible = false;

            }
            else
            {
                //gv.CssClass = "datalist1";
                //gv.CssClass = "datalist1";
                //gv.AlternatingRowStyle.CssClass = "GridView_AlternatingRowStyle";

                gv.AllowSorting = true;
                gv.ShowFooter = ShowFooter;

                //this.GridViewDataSource = ds.Tables[0];
                gv.DataSource = ds;
                gv.DataBind();
                gvm.Visible = gv.Rows.Count > 0;
                //gv.FooterRow

            }
        }
        #endregion

        #region 无数据的行进行重现(用于回调时没有对GridView进行绑定操作的情况)
        public void RenderGridViewNullRow(ref GridView gv, ref Mobile.Controls.GVPageManager gvm)
        {
            try
            {
                string empty = string.Empty;
                if (string.IsNullOrEmpty(gv.EmptyDataText))
                    empty = EMPTY_DATA_STYLE;
                else
                    empty = gv.EmptyDataText;
                if ((gv.Rows.Count == 0) ||
                    (gv.Rows.Count == 1 && gv.Rows[0].Cells.Count > 0 && gv.Rows[0].Cells[0].Text == empty))
                    GVDataBind(ref gv, ref gvm, null);
            }
            catch { }
        }
        #endregion

        #region 对GridView的绑定事件进行封装
        public void RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //此方法已移除，不再使用。
        }
        /// <summary>
        /// 对GridView的行数据绑定事件进行封装，主要用户计算Footer。
        /// 使用时在页面的page_load事件中添加 GridView1.RowDataBound += RowDataBound;
        /// 并在GridView的字段属性中内增加 FooterText="sum(srcBalance)" 例如：
        /// <asp:BoundField HeaderText="余额" DataField="srcBalance" DataFormatString="{0:0.000#}" FooterText="sum(srcBalance)"/>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void GridViewRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                #region 计算FooterText内的表达式
                GridView gv = sender as GridView;
                if (gv == null) return;

                for (int i = 0; i < gv.Columns.Count; i++)
                {
                    try
                    {
                        DataControlField col = gv.Columns[i];
                        string Expression = string.Empty;
                        object result;
                        decimal Aggregate = 0.000M;
                        string ExpressionFormatStr = string.Empty;

                        try
                        {
                            ExpressionFormatStr = ((BoundField)col).DataFormatString;
                        }
                        catch { }

                        Expression = col.FooterText;
                        if (string.IsNullOrEmpty(Expression)) continue;
                        GridView _gv = sender as GridView;
                        if (_gv != null)
                        {
                            DataTable dt = null;
                            if (_gv.DataSource.GetType().ToString().ToLower() == "system.data.datatable")
                            {
                                dt = _gv.DataSource as DataTable;
                            }
                            else if (_gv.DataSource.GetType().ToString().ToLower() == "system.data.dataview")
                            {
                                DataView dv_tmp = _gv.DataSource as DataView;
                                if (dv_tmp != null)
                                    dt = dv_tmp.ToTable();
                            }
                            else if (_gv.DataSource.GetType().ToString().ToLower() == "system.data.dataset")
                            {
                                DataSet ds_tmp = _gv.DataSource as DataSet;
                                if (ds_tmp != null && ds_tmp.Tables.Count > 0)
                                    dt = ds_tmp.Tables[0];
                            }
                            if (dt != null)
                                result = dt.Compute(Expression, "");
                            else
                                result = 0;
                        }
                        else
                            result = 0;

                        if (Expression.ToLower().IndexOf("sum(") >= 0)
                        {
                            for (int m = 0; m < gv.Rows.Count; m++)
                            {
                                col.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                                col.FooterStyle.HorizontalAlign = HorizontalAlign.Right;
                                decimal tmp = 0.000M;
                                try
                                {
                                    string colname = Expression.Replace("sum(", "").Replace(")", "");
                                    if (gv.DataKeys.Count > 0 && gv.DataKeys[m][colname] != null)
                                    {
                                        tmp = Convert.ToDecimal(gv.DataKeys[m][colname]);
                                    }
                                    else
                                    {
                                        string inner = string.Empty;
                                        inner = Helper.ControlInnerText(gv.Rows[m].Cells[i]);
                                        tmp = Convert.ToDecimal(inner);
                                    }
                                }
                                catch { }
                                Aggregate += tmp;
                            }
                        }

                        switch (result.GetType().FullName.ToLower())
                        {
                            case "system.decimal":
                            case "system.double":
                            case "system.single":
                            case "system.int16":
                            case "system.uint16":
                            case "system.int32":
                            case "system.uint32":
                            case "system.int64":
                            case "system.uint64":
                                if (Expression.ToLower().IndexOf("sum(") >= 0)
                                {
                                    e.Row.Cells[i].Text = string.Format(string.IsNullOrEmpty(ExpressionFormatStr) ? "{0:0.000#}" : ExpressionFormatStr, Aggregate);
                                    e.Row.Cells[i].Text += "<br/>";
                                    e.Row.Cells[i].Text += string.Format(string.IsNullOrEmpty(ExpressionFormatStr) ? "{0:0.000#}" : ExpressionFormatStr, result);
                                }
                                else
                                    e.Row.Cells[i].Text = string.Format(string.IsNullOrEmpty(ExpressionFormatStr) ? "{0:0.000#}" : ExpressionFormatStr, result);
                                break;
                            default:
                                e.Row.Cells[i].Text = string.Format(string.IsNullOrEmpty(ExpressionFormatStr) ? "{0}" : ExpressionFormatStr, result);
                                break;
                        }



                    }
                    catch { }
                }
                #endregion
            }
            else if (e.Row.RowType == DataControlRowType.Header)
            {
                //GridView gvData = sender as GridView;
                //GridViewRow gvRow = e.Row;
                //for (int index = 0; index <= gvData.Columns.Count - 1; index++)
                //{
                //    if ((gvSortExpression.IndexOf(gvData.Columns[index].SortExpression) >= 0) && (gvData.Columns[index].SortExpression != ""))
                //    {
                //        Image img = new Image();

                //        if ((string)ViewState["sort"] == "asc")
                //        {
                //            img.ImageUrl = "~/Images/SortUp.gif";
                //            img.ToolTip = "递增排列";
                //        }
                //        else
                //        {
                //            img.ImageUrl = "~/Images/SortDown.gif";
                //            img.ToolTip = "递减排列";
                //        }
                //        gvRow.Cells[index].Controls.Add(img);
                //    }
                //}
            }
        }

        protected void GridViewRowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "sort")
            {
                gvSortExpression = e.CommandArgument.ToString() + " " + ViewState["sort"].ToString();
                return;
            }
        }

        protected void GridViewSorting(object sender, GridViewSortEventArgs e)
        {
            GridView tmp = (GridView)sender;
            SortGridView(ref tmp, GridViewDataSource, e);
        }

        protected void GridViewDataBinding(object sender, EventArgs e)
        {
            GridView gvData = (GridView)sender;
            for (int index = 0; index <= gvData.Columns.Count - 1; index++)
            {
                string Head = gvData.Columns[index].HeaderText;
                Head = Head.Replace("↑", "");
                Head = Head.Replace("↓", "");
                gvData.Columns[index].HeaderText = Head;

                if ((gvSortExpression.IndexOf(gvData.Columns[index].SortExpression + " ") >= 0) && (gvData.Columns[index].SortExpression != ""))
                {
                    if ((string)ViewState["sort"] == "asc")
                    {
                        Head += "↓";
                        gvData.Columns[index].HeaderText = Head;
                    }
                    else
                    {
                        Head += "↑";
                        gvData.Columns[index].HeaderText = Head;
                    }
                }
            }
        }
        #endregion

        #region 获取批量选择的数据
        /// <summary>
        /// 获取批量选择的数据,GridView需要设置DataKeyNames，或者为CheckBox控件设置Attributes["value"]
        /// </summary>
        /// <param name="GVData"></param>
        /// <param name="CheckBoxID">选择控件的ID</param>
        /// <returns></returns>
        protected virtual ArrayList GetBatchSelect(GridView GVData, string CheckBoxID)
        {
            ArrayList List = new ArrayList();
            CheckBox cb_sel;
            string value = string.Empty;
            foreach (GridViewRow row in GVData.Rows)
            {
                cb_sel = row.FindControl(CheckBoxID) as CheckBox;
                if ((cb_sel == null) || (!cb_sel.Checked)) continue;
                if (GVData.DataKeys.Count > 0)
                    value = GVData.DataKeys[row.RowIndex].Value.ToString();
                else
                    value = cb_sel.Attributes["value"];
                try
                {
                    if (!string.IsNullOrEmpty(value))
                        List.Add(value);
                }
                catch { }

            }
            return List;
        }
        /// <summary>
        /// 获取批量选择的数据,GridView需要设置DataKeyNames，或者为CheckBox控件设置Attributes["value"]
        /// </summary>
        /// <param name="GVData"></param>
        /// <param name="CheckBoxID">选择控件的ID</param>
        /// <param name="KeyFieldName">KEY字段的名字</param>
        /// <returns></returns>
        protected virtual ArrayList GetBatchSelect(GridView GVData, string CheckBoxID, string KeyFieldName)
        {
            ArrayList List = new ArrayList();
            CheckBox cb_sel;
            string value = string.Empty;
            foreach (GridViewRow row in GVData.Rows)
            {
                cb_sel = row.FindControl(CheckBoxID) as CheckBox;
                if ((cb_sel == null) || (!cb_sel.Checked)) continue;
                if (GVData.DataKeys.Count > 0)
                    value = GVData.DataKeys[row.RowIndex][KeyFieldName].ToString();
                else
                    value = cb_sel.Attributes["value"];
                try
                {
                    if (!string.IsNullOrEmpty(value))
                        List.Add(value);
                }
                catch { }

            }
            return List;
        }
        #endregion

        #region 事件的备份与恢复
        #region 清除一个对象所有事件所挂钩的delegate
        /// <summary>
        /// 清除一个对象所有事件所挂钩的delegate
        /// </summary>
        /// <param name="objectHasEvents">有事件的对象</param>
        public static void ClearAllEvents(object objectHasEvents, EventInfo[] events)
        {
            if (objectHasEvents == null)
            {
                return;
            }

            if (events == null || events.Length < 1)
            {
                return;
            }

            for (int i = 0; i < events.Length; i++)
            {
                try
                {
                    EventInfo ei = events[i];

                    FieldInfo fi =
                        objectHasEvents.GetType().GetField("Event" + ei.Name,
                                                  BindingFlags.NonPublic |
                                                  BindingFlags.Instance |
                                                  BindingFlags.CreateInstance |
                                                  BindingFlags.DeclaredOnly |
                                                  BindingFlags.Default |
                                                  BindingFlags.ExactBinding |
                                                  BindingFlags.FlattenHierarchy |
                                                  BindingFlags.GetField |
                                                  BindingFlags.GetProperty |
                                                  BindingFlags.IgnoreCase |
                                                  BindingFlags.IgnoreReturn |
                                                  BindingFlags.InvokeMethod |
                                                  BindingFlags.OptionalParamBinding |
                                                  BindingFlags.Public |
                                                  BindingFlags.PutDispProperty |
                                                  BindingFlags.PutRefDispProperty |
                                                  BindingFlags.SetField |
                                                  BindingFlags.SetProperty |
                                                  BindingFlags.Static |
                                                  BindingFlags.SuppressChangeType);
                    if (fi != null)
                    {
                        // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate
                        fi.SetValue(objectHasEvents, null);
                    }
                }
                catch
                {
                }
            }
        }
        public static void ClearEvent(object objectHasEvents, string EventName)
        {
            if (objectHasEvents == null)
            {
                return;
            }

            try
            {
                FieldInfo fi =
                    objectHasEvents.GetType().GetField("Event" + EventName,
                                              BindingFlags.NonPublic |
                                              BindingFlags.Instance |
                                              BindingFlags.CreateInstance |
                                              BindingFlags.DeclaredOnly |
                                              BindingFlags.Default |
                                              BindingFlags.ExactBinding |
                                              BindingFlags.FlattenHierarchy |
                                              BindingFlags.GetField |
                                              BindingFlags.GetProperty |
                                              BindingFlags.IgnoreCase |
                                              BindingFlags.IgnoreReturn |
                                              BindingFlags.InvokeMethod |
                                              BindingFlags.OptionalParamBinding |
                                              BindingFlags.Public |
                                              BindingFlags.PutDispProperty |
                                              BindingFlags.PutRefDispProperty |
                                              BindingFlags.SetField |
                                              BindingFlags.SetProperty |
                                              BindingFlags.Static |
                                              BindingFlags.SuppressChangeType);
                if (fi != null)
                {
                    // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate
                    fi.SetValue(objectHasEvents, null);
                }
            }
            catch
            {
            }

        }
        #endregion

        #region 备份控件事件
        public static object[] BackupAllEvents(object objectHasEvents)
        {
            if (objectHasEvents == null)
            {
                return null;
            }

            EventInfo[] events = objectHasEvents.GetType().GetEvents(
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance);

            object[] result = new object[events.Length];

            for (int i = 0; i < events.Length; i++)
            {
                try
                {
                    EventInfo ei = events[i];

                    FieldInfo fi =
                        objectHasEvents.GetType().GetField("Event" + ei.Name,
                                                  BindingFlags.NonPublic |
                                                  BindingFlags.Instance |
                                                  BindingFlags.CreateInstance |
                                                  BindingFlags.DeclaredOnly |
                                                  BindingFlags.Default |
                                                  BindingFlags.ExactBinding |
                                                  BindingFlags.FlattenHierarchy |
                                                  BindingFlags.GetField |
                                                  BindingFlags.GetProperty |
                                                  BindingFlags.IgnoreCase |
                                                  BindingFlags.IgnoreReturn |
                                                  BindingFlags.InvokeMethod |
                                                  BindingFlags.OptionalParamBinding |
                                                  BindingFlags.Public |
                                                  BindingFlags.PutDispProperty |
                                                  BindingFlags.PutRefDispProperty |
                                                  BindingFlags.SetField |
                                                  BindingFlags.SetProperty |
                                                  BindingFlags.Static |
                                                  BindingFlags.SuppressChangeType);
                    if (fi != null)
                    {
                        // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate
                        result[i] = fi.GetValue(objectHasEvents);
                    }
                }
                catch
                {
                    result[i] = null;
                }
            }

            return result;
        }
        public static object BackupEvent(object objectHasEvents, string EventName)
        {
            if (objectHasEvents == null)
            {
                return null;
            }

            try
            {
                FieldInfo fi =
                            objectHasEvents.GetType().GetField("Event" + EventName,
                                                      BindingFlags.NonPublic |
                                                      BindingFlags.Instance |
                                                      BindingFlags.CreateInstance |
                                                      BindingFlags.DeclaredOnly |
                                                      BindingFlags.Default |
                                                      BindingFlags.ExactBinding |
                                                      BindingFlags.FlattenHierarchy |
                                                      BindingFlags.GetField |
                                                      BindingFlags.GetProperty |
                                                      BindingFlags.IgnoreCase |
                                                      BindingFlags.IgnoreReturn |
                                                      BindingFlags.InvokeMethod |
                                                      BindingFlags.OptionalParamBinding |
                                                      BindingFlags.Public |
                                                      BindingFlags.PutDispProperty |
                                                      BindingFlags.PutRefDispProperty |
                                                      BindingFlags.SetField |
                                                      BindingFlags.SetProperty |
                                                      BindingFlags.Static |
                                                      BindingFlags.SuppressChangeType);
                if (fi != null)
                {
                    // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate
                    return fi.GetValue(objectHasEvents);
                }
                else
                    return null;
            }
            catch { return null; }
        }
        #endregion

        #region 恢复控件事件
        public static void RestoreAllEvents(object objectHasEvents, object[] datas)
        {
            if (objectHasEvents == null)
            {
                return;
            }

            EventInfo[] events = objectHasEvents.GetType().GetEvents(
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance);

            if (datas == null || datas.Length < 1) return;

            if (events == null || events.Length < 1) return;

            if (events.Length != datas.Length) return;

            for (int i = 0; i < datas.Length; i++)
            {
                try
                {
                    EventInfo ei = events[i];

                    FieldInfo fi =
                        objectHasEvents.GetType().GetField("Event" + ei.Name,
                                                  BindingFlags.NonPublic |
                                                  BindingFlags.Instance |
                                                  BindingFlags.CreateInstance |
                                                  BindingFlags.DeclaredOnly |
                                                  BindingFlags.Default |
                                                  BindingFlags.ExactBinding |
                                                  BindingFlags.FlattenHierarchy |
                                                  BindingFlags.GetField |
                                                  BindingFlags.GetProperty |
                                                  BindingFlags.IgnoreCase |
                                                  BindingFlags.IgnoreReturn |
                                                  BindingFlags.InvokeMethod |
                                                  BindingFlags.OptionalParamBinding |
                                                  BindingFlags.Public |
                                                  BindingFlags.PutDispProperty |
                                                  BindingFlags.PutRefDispProperty |
                                                  BindingFlags.SetField |
                                                  BindingFlags.SetProperty |
                                                  BindingFlags.Static |
                                                  BindingFlags.SuppressChangeType);
                    if (fi != null)
                    {
                        // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate
                        fi.SetValue(objectHasEvents, datas[i]);
                    }
                }
                catch
                {
                }
            }
        }

        public static void RestoreEvent(object objectHasEvents, string EventName, object EventObject)
        {
            if (objectHasEvents == null)
            {
                return;
            }

            if (EventObject == null)
            {
                return;
            }

            try
            {
                FieldInfo fi =
                    objectHasEvents.GetType().GetField("Event" + EventName,
                                              BindingFlags.NonPublic |
                                              BindingFlags.Instance |
                                              BindingFlags.CreateInstance |
                                              BindingFlags.DeclaredOnly |
                                              BindingFlags.Default |
                                              BindingFlags.ExactBinding |
                                              BindingFlags.FlattenHierarchy |
                                              BindingFlags.GetField |
                                              BindingFlags.GetProperty |
                                              BindingFlags.IgnoreCase |
                                              BindingFlags.IgnoreReturn |
                                              BindingFlags.InvokeMethod |
                                              BindingFlags.OptionalParamBinding |
                                              BindingFlags.Public |
                                              BindingFlags.PutDispProperty |
                                              BindingFlags.PutRefDispProperty |
                                              BindingFlags.SetField |
                                              BindingFlags.SetProperty |
                                              BindingFlags.Static |
                                              BindingFlags.SuppressChangeType);
                if (fi != null)
                {
                    // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate
                    fi.SetValue(objectHasEvents, EventObject);
                }
            }
            catch
            {
            }

        }
        #endregion
        #endregion

        #region 解决ViewState过于庞大的问题
        //由于这里添加了目录,所以要建立App_Data/ViewState目录.
        protected override object LoadPageStateFromPersistenceMedium()
        {
            try
            {
                string viewStateID = (string)((Pair)base.LoadPageStateFromPersistenceMedium()).Second;
                string stateStr = (string)Cache[viewStateID];
                if (stateStr == null)
                {
                    string fn = Path.Combine(this.Request.PhysicalApplicationPath, @"App_Data/ViewState/" + viewStateID);
                    stateStr = File.ReadAllText(fn);
                }
                return new ObjectStateFormatter().Deserialize(stateStr);
            }
            catch
            {
                throw new Mobile.ViewStateCacheTimeOutException("您长时间没有进行操作了，请重新打开页面。");
            }
        }

        protected override void SavePageStateToPersistenceMedium(object state)
        {
            string value = new ObjectStateFormatter().Serialize(state);
            string viewStateID = (DateTime.Now.Ticks + (long)this.GetHashCode()).ToString(); //产生离散的id号码
            string fn = Path.Combine(this.Request.PhysicalApplicationPath, @"App_Data/ViewState/" + viewStateID);
            try
            {
                //ThreadPool.QueueUserWorkItem(File.WriteAllText(fn, value));
                File.WriteAllText(fn, value);
            }
            catch { }
            Cache.Insert(viewStateID, value);
            base.SavePageStateToPersistenceMedium(viewStateID);
        }
        #endregion

        #region  添加日志
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="content">日志内容</param>
        public bool AddLog(string content)
        {
            //模块名称根据最后打开一个页面的MID或者模块名称来确定。增加一列记录页面的名称。
            try
            {
                string SysMid = Session["ModuleId"] == null ? "" : Session["ModuleId"].ToString();
                Hashtable operLogInfo = new Hashtable();
                //记录操作日志
                operLogInfo["userid"] = GetParaValue("userid");
                operLogInfo["loginid"] = GetParaValue("username");
                operLogInfo["modulename"] = SysMid;
                operLogInfo["usertype"] = GetParaValue("usertype");
                operLogInfo["content"] = content;
                operLogInfo["url"] = Request.RawUrl;
                operLogInfo["id"] = "0";

                operLogInfo["localip"] = NetSocket.getAllIp();
                operLogInfo["operdate"] = DateTime.Now;
                operLogInfo["isdel"] = "0";
                ERMap.ERMapHelper.setmodel("OperatorLog", "id", operLogInfo);
                return true;
            }
            catch { return false; }
        }

        public bool AddLog(string ModuleId, string content)
        {
            //模块名称根据最后打开一个页面的MID或者模块名称来确定。增加一列记录页面的名称。
            try
            {
                //string SysMid = Session["ModuleId"] == null ? "" : Session["ModuleId"].ToString();
                Hashtable operLogInfo = new Hashtable();
                //记录操作日志
                operLogInfo["userid"] = GetParaValue("userid");
                operLogInfo["loginid"] = GetParaValue("username");
                operLogInfo["modulename"] = ModuleId;
                operLogInfo["usertype"] = GetParaValue("usertype");
                operLogInfo["content"] = content;
                operLogInfo["url"] = Request.RawUrl;
                operLogInfo["id"] = "0";

                operLogInfo["localip"] = NetSocket.getAllIp();
                operLogInfo["operdate"] = DateTime.Now;
                operLogInfo["isdel"] = "0";
                ERMap.ERMapHelper.setmodel("OperatorLog", "id", operLogInfo);
                return true;
            }
            catch { return false; }
        }
        public bool AddLog(string content, params object[] param)
        {
            return AddLog(string.Format(content, param));
        }
        #endregion

        #region 关闭窗口时执行打开窗口的查询
        public void RegClickOperQueryScript(string BtnId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("function _ClickOperQuery(){");
            sb.Append("    if (window.opener !=null)");
            sb.Append("    {");
            sb.Append("        var qry = window.opener.document.getElementById('");
            sb.Append(BtnId);
            sb.Append("');");
            sb.Append("        if (qry != null) qry.click();else window.opener.location.href = window.opener.location.href;");
            sb.Append("    }");
            sb.Append("}");

            //sb.Append("addEvent(window,'unload',ClickOperQuery);");
            sb.Append("if (_addEvent) _addEvent(window,'unload',_ClickOperQuery);");

            ClientScript.RegisterClientScriptBlock(Page.GetType(), "ClickOperQuery", ScriptBuilder.GetScriptBlock(sb.ToString()));

        }
        #endregion

        #region 新的分页控件绑定repeater部分

        public void SetDivePage(ref PagedDataSource pdds, ref Mobile.Controls.Page gvm, ref Repeater rpt)
        {
            int RecordNum = 10;
            if (pdds.PageSize > 0)
                RecordNum = pdds.PageSize;
            //绑定事件
            Mobile.Controls.BindDataDelegate_NewPage f = new Mobile.Controls.BindDataDelegate_NewPage(QueryData);
            //设置分页
            SetDivePage(ref pdds, ref gvm, f, RecordNum, ref rpt);
        }

        /// <summary>
        /// 绑定分页
        /// </summary>
        public void SetDivePage(ref PagedDataSource pdds, ref Mobile.Controls.Page gvm, int RecordNum, ref Repeater rpt)
        {
            //绑定事件
            Mobile.Controls.BindDataDelegate_NewPage f = new Mobile.Controls.BindDataDelegate_NewPage(QueryData);
            //设置分页
            SetDivePage(ref pdds, ref gvm, f, RecordNum, ref rpt);
        }

        /// <summary>
        /// 绑定分页
        /// </summary>
        public void SetDivePage(ref PagedDataSource pdds, ref Mobile.Controls.Page gvm, Mobile.Controls.BindDataDelegate_NewPage f, int RecordNum, ref Repeater rpt)
        {

            //设置分页
            gvm.SetTarget(pdds, f, RecordNum, rpt);
        }


        public void RenderGridViewNullRow(ref Repeater gv, ref Mobile.Controls.Page gvm)
        {
            try
            {
                //string empty = string.Empty;
                //if (string.IsNullOrEmpty(gv.EmptyDataText))
                //    empty = EMPTY_DATA_STYLE;
                //else
                //    empty = gv.EmptyDataText;
                //if ((gv.Rows.Count == 0) ||
                //    (gv.Rows.Count == 1 && gv.Rows[0].Cells.Count > 0 && gv.Rows[0].Cells[0].Text == empty))
                //    GVDataBind(ref gv, ref gvm, null);
            }
            catch { }
        }

        /// <summary>
        /// 绑定数据集
        /// </summary>
        /// <param name="gv">GridView控件</param>
        /// <param name="gvm">分页控件</param>
        /// <param name="ds">数据集</param>
        public void GVDataBind(ref Repeater gv, ref Mobile.Controls.Page gvm, ref PagedDataSource pdds)
        {
            //if ((ds == null) || (ds.Tables.Count == 0) || (ds.Tables[0].Rows.Count == 0))
            if (pdds.PageCount == 0)
            {
                gvm.Visible = false;
                Literal li = new Literal();
                li.Text = "<span style='display:block;padding:20px;color:#666'>    暂无数据！</span>";
                gv.Controls.Add(li);
            }
            else
            {
                gvm.Visible = true;
                gv.DataSource = pdds;
                gv.DataBind();
            }
        }
        #endregion
    }

    /// <summary>
    /// 帮助类
    /// </summary>
    public class Helper
    {
        public static void Model2ViewState(Hashtable model, StateBag ViewState)
        {
            foreach (DictionaryEntry de in model)
            {
                ViewState[de.Key.ToString()] = de.Value;
            }
        }

        #region 获取HTML控件内的文本
        public static string ControlInnerText(Control textctl)
        {
            StringBuilder result = new StringBuilder();

            string tmp = Commons.StrUtil.FormatValue(Commons.AsmUtil.GetPropertyValue(textctl, "Text", null));
            tmp = FormatHtmlInnerText(tmp.Trim()).Trim();
            if (!string.IsNullOrEmpty(tmp))
            {
                result.Append(tmp);
                result.Append(" ");
            }
            foreach (Control ctl in textctl.Controls)
                result.Append(ControlInnerText(ctl));
            return result.ToString();
        }
        #endregion



        #region 获取html字符串的innertext
        public static string FormatHtmlInnerText(string AHtml)
        {
            return Commons.StringUtil.FormatHtmlInnerText(AHtml);
        }
        #endregion

        #region 替换html字符
        public static string ReplaceMarkupChar(string source)
        {
            return Commons.StringUtil.ReplaceMarkupChar(source);
        }
        #endregion
    }
}